package cn.sunshine.ymcc.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign的拦截器
 */
@Component
public class TokenForwordFeignInterceptor implements RequestInterceptor{

        /*
         * @Title: apply
         * @Description: 将当前请求的请求头中的token携带给Feign的请求头
         * @Author: Mr.Jiang
         * @Version: 1.0
         * @Date:  2022/8/27 23:27
         * @Parameters: [requestTemplate]
         * @Return void
         */
        @Override
        public void apply(RequestTemplate requestTemplate) {
            //1.拿到当前请求
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            //2.得到请求头中的token
            String token = request.getHeader("Authorization");
            if (StringUtils.hasLength(token))
                //3.设置给下一个请求头
                requestTemplate.header("Authorization", token);
            }
        }
